import React from 'react'
import { connect } from 'dva'
import { Table, Form, Input, Select, DatePicker, Button, Modal, Popconfirm, message, Upload, InputNumber, Icon } from 'antd';
const dateFormat = 'YYYY-MM-DD';
import moment from 'moment';
const R = require("ramda");

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
import RightContacts from "../../../utils/RightConstants";
import RightBox from "../../../components/commons/RightBox";
import Constants from "../../../utils/Constants";

const ExchangeRate = ({ routes, params, children, location, dispatch, exchangeRate }) => {
    const { page, search, list, editModel, upload } = exchangeRate;

    const columns = [{
        title: '币种代码',
        dataIndex: 'code',
        key: 'code',
    }, {
        title: '币种名称',
        dataIndex: 'name',
        key: 'name',
    }, {
        title: '目标币种',
        dataIndex: 'targetcurrency',
        key: 'targetcurrency',
    }, {
        title: '汇率',
        dataIndex: 'rate',
        key: 'rate',
    }, {
        title: '创建时间',
        dataIndex: 'createtime',
        key: 'createtime',
    }, {
        title: '汇率时间',
        dataIndex: 'ratetime',
        key: 'ratetime',
    }, {
        title: '操作',
        render(record) {
            let editRateButton =
                <RightBox resource={RightContacts.BASEDATA.BASE_RATE_EDIT}><a href="#" onClick={
                    () => {
                        dispatch({
                            type: 'exchangeRate/getCurrencyRateById',
                            payload: {
                                id: record.id
                            }
                        })
                    }
                }>编辑</a>

                    <span className="ant-divider" /></RightBox>;
            let deleteRateButton = <RightBox resource={RightContacts.BASEDATA.BASE_RATE_DELETE}>
                <Popconfirm placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除？'} onConfirm={() => {
                    dispatch({
                        type: 'exchangeRate/deleteCurrencyRate',
                        payload: {
                            id: record.id
                        }
                    });
                }} okText="是" cancelText="否">
                    <a href="#">删除</a>
                </Popconfirm>
            </RightBox>;


            return (
                <span>
                    {editRateButton}
                    {deleteRateButton}

                </span>
            );
        }
    }];

    const handleAdd = function () {
        dispatch({
            type: 'exchangeRate/setEditModel',
            payload: {
                showStatus: true,
                title: '创建汇率',
                type: 'add',
                form: {
                    code: '',
                    name: '',
                    targetcurrency: 'USD',
                    rate: '',
                    status: '1'
                }
            }
        });
    };
    const handleUpload = function () {
        dispatch({
            type: "exchangeRate/setUpload",
            payload: {
                showStatus: true,
                confirmLoading: false,
                title: "上传文件"
            }
        })
    }

    const synchronizeCurrencyRate = function () {
        dispatch({ type: "exchangeRate/synchronizeCurrencyRate" })
    }

    const SearchForm = Form.create()(({ form }) => {
        const { getFieldDecorator, validateFields } = form;

        const handleSearch = function () {
            validateFields((errors, values) => {
                let times = values.ratetime;
                if (errors) {
                    return
                }
                dispatch({
                    type: 'exchangeRate/setSearch', payload: {
                        search: {
                            code: values.code,
                            name: values.name,
                            status: values.status,
                            ratetime: values.ratetime,
                            beginTime: times && times[0] ? times[0].format(dateFormat) : null,
                            endTime: times && times[1] ? times[1].format(dateFormat) : null,
                        }
                    }
                });
                let newPage = page;
                newPage.page = 1;
                dispatch({
                    type: 'exchangeRate/setPage', payload: {
                        page: newPage
                    }
                });
                dispatch({ type: 'exchangeRate/querCurrencyRateList' });
            });
        }

        return (
            <div>
                <Form layout="inline" style={{ marginBottom: 15 }}>
                    <FormItem label={'币种代码'}>
                        {getFieldDecorator('code', { initialValue: search.code })(
                            <Input style={{ width: 100 }} maxLength="10"/>
                        )}
                    </FormItem>
                    <FormItem label={'币种名称'}>
                        {getFieldDecorator('name', { initialValue: search.name })(
                            <Input style={{ width: 100 }} maxLength="20"/>
                        )}
                    </FormItem>

                    <FormItem label={'汇率时间'}>
                        {getFieldDecorator('ratetime', {
                            initialValue:
                            [R.isNil(search.beginTime) ? '' : moment(search.beginTime, dateFormat), R.isNil(search.endTime) ? '' : moment(search.endTime, dateFormat)]
                        })(
                            <RangePicker
                                showTime={{ format: 'YYYY-MM-DD' }}
                                format="YYYY-MM-DD"
                                placeholder={['开始时间', '结束时间']}
                            />
                            )}
                    </FormItem>
                    <Button type="primary" icon="search" style={{ marginRight: 15 }} onClick={handleSearch}>查询</Button>
                    <RightBox style={{ marginRight: 15 }} resource={RightContacts.BASEDATA.BASE_RATE_ADD}><Button icon="plus" onClick={handleAdd}>添加汇率</Button></RightBox>
                    <RightBox style={{ marginRight: 15 }} resource={RightContacts.BASEDATA.BASE_RATE_ADD}><Button icon="plus" onClick={handleUpload}>上传汇率文件</Button></RightBox>
                    <RightBox resource={RightContacts.BASEDATA.BASE_RATE_SYNC}><Button onClick={synchronizeCurrencyRate}>同步汇率</Button></RightBox>
                </Form>
            </div>
        );

    });

    return (
        <div>
            <EditExchangeRate visible={editModel.showStatus} title={editModel.title} confirmLoading={editModel.confirmLoading}
                dispatch={dispatch} editModel={editModel} />

            <Uploader visible={upload.showStatus} upload={upload} dispatch={dispatch} confirmLoading={upload.confirmLoading} />
            <SearchForm />

            <Table rowKey="id" dataSource={list} columns={columns} bordered={false} size={'middle'} pagination={{
                showTotal: total => `共 ${total} 条数据`,
                pageSize: page.size,
                total: page.totalRow,
                showSizeChanger: true,
                current: page.page,
                onShowSizeChange: (current, size) => {
                    let newPage = page;
                    newPage.size = size;
                    newPage.page = 1;
                    dispatch({
                        type: 'exchangeRate/setPage', payload: {
                            page: newPage
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = page;
                    newPage.page = pageNumber;
                    dispatch({
                        type: 'exchangeRate/setPage', payload: {
                            page: newPage
                        }
                    });
                    dispatch({ type: 'exchangeRate/querCurrencyRateList' });

                }
            }} />
        </div>

    );


}

const Uploader = ({ upload, dispatch, confirmLoading }) => {
    const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 6 },
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 14 },
        },
    };

    const UploadForm = Form.create()(({ form }) => {
        const { getFieldDecorator, validateFields } = form;
        let headers = { [Constants.ACJSESSIONID]: sessionStorage.getItem(Constants.ACJSESSIONID) };
        let footer = [];
        footer.push(<Button loading={upload.confirmLoading} onClick={
            () => {
                validateFields((errors, values) => {
                    if (errors) {
                        return;
                    }
                    let file = R.isNil(values.file) ? null : values.file.fileList;

                    if (R.isNil(file) || R.isEmpty(file)) {
                        message.error("请选择上传文件");
                        return;
                    }
                    if (file[0].response.status == 500) {
                        message.error(file[0].response.message);
                        return;
                    }
                    dispatch({
                        type: "exchangeRate/setUpload",
                        payload: {
                            confirmLoading: true,
                        }
                    })
                    let fileurl = file[0].response.content["0"].url;

                    dispatch({
                        type: "exchangeRate/uploadRate",
                        payload: {
                            file: fileurl
                        }
                    })

                })
            }
        }>确认</Button>)

        return (
            <Modal maskClosable={false} visible={upload.showStatus} title={upload.title} confirmLoading={confirmLoading} onCancel={
                () => {
                    dispatch({
                        type: 'exchangeRate/setUpload',
                        payload: {
                            showStatus: false,
                            confirmLoading: false,
                        }
                    });
                }
            }
                footer={footer}

            >
                <Form>
                    <FormItem {...formItemLayout}>
                        {getFieldDecorator("file", {
                        })(
                            <Upload.Dragger action={apiPath.zbtim + "/api/file/batch/currency/upload"} headers={headers} multiple={false} beforeUpload={
                                (file) => {
                                    const isLtMax = file.size / 1024 / 1024 < 20;
                                    let validateFileType = R.contains(file.name.substr(file.name.lastIndexOf('.') + 1), ['xls', 'xlsx']);
                                    if (!isLtMax) message.error(`文件大小超过${20}M限制`);
                                    if (!validateFileType) message.error("文件后缀非法,只允许xls|xlsx");
                                    return isLtMax && validateFileType;
                                }
                            }>
                                <Button>
                                    <Icon type="upload" />点击上传汇率表格
                                </Button>
                            </Upload.Dragger>
                            )}
                    </FormItem>

                </Form>


            </Modal>
        )
    });
    return (
        <UploadForm />
    )
}


const EditExchangeRate = ({ visible, title, editModel, dispatch, confirmLoading }) => {

    const formItemLayout = {
        labelCol: {
            xs: { span: 24 },
            sm: { span: 6 },
        },
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 14 },
        },
    };

    let xform = editModel.form;

    const WrappedForm = Form.create()(({ form }) => {
        const { getFieldDecorator, validateFields } = form;
        return (
            <Modal maskClosable={false} visible={visible} title={title} confirmLoading={confirmLoading} onCancel={
                () => {
                    dispatch({
                        type: 'exchangeRate/setEditModel',
                        payload: {
                            showStatus: false
                        }
                    });
                }
            } onOk={
                () => {
                    validateFields((errors, values) => {
                        if (errors) {
                            return
                        }

                        if (editModel.type === "add") {
                            dispatch({
                                type: 'exchangeRate/addCurrencyRate',
                                payload: {
                                    code: values.code,
                                    name: values.name,
                                    targetcurrency: values.targetcurrency,
                                    rate: values.rate,
                                    status: values.status,
                                    ratetime: values.ratetime.format(dateFormat),
                                }
                            });
                        } else {
                            dispatch({
                                type: 'exchangeRate/updateCurrencyRate',
                                payload: {
                                    id: xform.id,
                                    code: values.code,
                                    name: values.name,
                                    targetcurrency: values.targetcurrency,
                                    rate: values.rate,
                                    status: values.status,
                                    ratetime: values.ratetime.format(dateFormat),
                                }
                            });
                        }
                    });
                }
            }>

                <Form>
                    <FormItem
                        {...formItemLayout}
                        label="币种代码"
                        hasFeedback
                    >
                        {getFieldDecorator('code', {
                            rules: [{
                                required: true, message: '请输入币种代码',
                            }],
                            initialValue: xform.code
                        })(
                            <Input maxLength="10"/>
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="币种名称"
                        hasFeedback
                    >
                        {getFieldDecorator('name', {
                            rules: [{
                                required: true, message: '请输入币种名称',
                            }],
                            initialValue: xform.name
                        })(
                            <Input maxLength="20"/>
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="目标币种"
                        hasFeedback
                    >
                        {getFieldDecorator('targetcurrency', {
                            rules: [{
                                required: true, message: '请输入目标币种',
                            }],
                            initialValue: xform.targetcurrency
                        })(
                            <Select>
                                <Option value="CNY">CNY（人民币）</Option>
                                <Option value="USD">USD（美元）</Option>
                            </Select>
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="汇率"
                        hasFeedback
                    >
                        {getFieldDecorator('rate', {
                            rules: [{
                                required: true, message: '请输入汇率',
                            }],
                            initialValue: xform.rate
                        })(
                            <InputNumber style={{ width: '100%' }} maxLength="18"/>
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="汇率时间"
                        hasFeedback
                    >
                        {getFieldDecorator('ratetime', {
                            rules: [{
                                required: true, message: '请输入汇率时间',
                            }],
                            initialValue: R.isNil(xform.ratetime) ? '' : moment(xform.ratetime, dateFormat)
                        })(
                            <DatePicker style={{ width: '100%' }}
                                showTime={{ format: 'YYYY-MM-DD' }}
                                format="YYYY-MM-DD"
                                placeholder="请选择时间"
                            />
                            )}
                    </FormItem>
                    {/*<FormItem*/}
                    {/*{...formItemLayout}*/}
                    {/*label="状态"*/}
                    {/*hasFeedback*/}
                    {/*>*/}
                    {/*{getFieldDecorator('status', {*/}
                    {/*rules: [{*/}
                    {/*required: true, message: '请输入状态',*/}
                    {/*}],*/}
                    {/*initialValue: xform.status*/}
                    {/*})(*/}
                    {/*<Select>*/}
                    {/*<Option value="1">生效</Option>*/}
                    {/*<Option value="0">失效</Option>*/}
                    {/*</Select>*/}
                    {/*)}*/}
                    {/*</FormItem>*/}
                </Form>
            </Modal>
        );
    });


    return (
        <WrappedForm />
    );
}

export default connect(({ exchangeRate }) => ({ exchangeRate }))(ExchangeRate)
